package cn.learn.util;

import lombok.extern.slf4j.Slf4j;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author huangyezhan
 * @version 1.0
 * @date 2021年09月06日22:08
 */
@Slf4j
public class BeanUtil {
    /**
     * bean转map
     *
     * @param source 数据来源
     * @param target 目标
     */
    public static void Bean2Map(Object source, Map target) throws Exception {
        try {
            BeanInfo             beanInfo            = Introspector.getBeanInfo(source.getClass(), Object.class);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key    = property.getName();
                Method getter = property.getReadMethod();
                Object value  = getter.invoke(source);
                target.put(key, value);
            }
        } catch (IntrospectionException e) {
            log.error("后去bean属性异常：{}", e.getMessage(), e);
            throw e;
        } catch (IllegalAccessException e) {
            log.error("获取属性发生权限异常:{}", e.getMessage(), e);
            throw e;
        } catch (InvocationTargetException e) {
            log.error("反射获取方法内部的异常：{}", e.getMessage(), e);
            throw e;
        }
    }
}
